package com.boruan.shengtangfeng.api.jwt.handler;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import com.alibaba.fastjson.JSON;
import com.boruan.shengtangfeng.core.utils.GlobalReponse;
import com.boruan.shengtangfeng.core.utils.GlobalReponseResultEnum;

public class LoginFailureHandler implements AuthenticationFailureHandler {
	@Override
	public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
			AuthenticationException e) throws IOException, ServletException {
		httpServletResponse.setContentType("application/json;charset=UTF-8");
		GlobalReponseResultEnum authorizeResultEnum;
		GlobalReponse globalReponse;
		if (e instanceof UsernameNotFoundException) {/** 用户不存在 **/
			authorizeResultEnum = GlobalReponseResultEnum.USER_NOT_EXIST;
		} else if (e instanceof BadCredentialsException) { /** 密码不正确 */
			authorizeResultEnum = GlobalReponseResultEnum.PASSWORD_IS_WRONG;
		} else if (e instanceof LockedException) {/** 账号被禁用 **/
			authorizeResultEnum = GlobalReponseResultEnum.USER_IS_DISABLED;
		} else { /** 无效的token **/
			authorizeResultEnum = GlobalReponseResultEnum.TOKEN_ERROR;
		}
		globalReponse = new GlobalReponse(authorizeResultEnum);
		httpServletResponse.getWriter().write(JSON.toJSONString(globalReponse));
	}
}
